package com.soso.j.spider.filter;

import java.io.IOException;
import java.util.TimeZone;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.soso.j.spider.queue.api.impl.QueueServiceImpl;
import com.soso.j.spider.service.impl.CacheServiceImpl;
import com.soso.j.spider.service.impl.CrawlInfoServiceImpl;
import com.soso.spider.bussiness.SpiderBussiness;
import com.soso.spider.bussiness.impl.SpiderBussinessImpl;
import com.soso.spider.context.SpiderContext;

/**
 * 
 * @author speed
 *
 */
public class ContextFilter  implements Filter{
  
    public void doFilter(ServletRequest request, ServletResponse response, 
    		FilterChain chain) throws IOException, ServletException {
    	TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
    	SpiderContext ctx = SpiderContext.getInstance();
    	ctx.setRequest((HttpServletRequest)request);
    	ctx.setResponse((HttpServletResponse)response);

    	if(ctx.getCacheService()==null){
    		ctx.setCacheService(new CacheServiceImpl());
    	}
    	if(ctx.getQueueService()==null){
    		ctx.setQueueService(new QueueServiceImpl());
    	}
    	if(ctx.getSpiderBussiness()==null){
    		SpiderBussiness spiderBussiness=new SpiderBussinessImpl();
        	spiderBussiness.setCrawlInfoService(new CrawlInfoServiceImpl());
        	ctx.setSpiderBussiness(spiderBussiness);
    	}
    	ctx.init();
     	chain.doFilter(request, response);
    	ctx.destory();
    }

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	

}
